#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "bt_data.h"
#include "btree.h"
#include "Error.h"
#include "word.h"

/* Supports strings sizes up to 255 (yes 255!) 
 * characters */
#define BUFFER_SIZE 256

void get_words (char *file, BTree *tree, FreqField field)
{
	FILE *f;
	unsigned int size;
	char buff[BUFFER_SIZE];
	char *word;

	if ((f = fopen (file, "r")) == NULL)
		Die ("Failed to open input file %s\n", file);

	/* According to Roman L.; if either file is empty, then nothing
	 * can trend, so just quit here. */
	if (fgets (buff, BUFFER_SIZE, f) == NULL) {
		fclose (f);
		Die ("Empty file detected; trending statistics unavailable\n");
	}

	/* Evil index magic to get rid of the new line char that fgets
	 * insists on copying; replaces it with a null character */
	size = strlen (buff);
	word = (char *) malloc (sizeof (char) * (size));
	strncpy (word, buff, size);
	word[size-1] = '\0';

	/* Reading the file for the first - binary tree created initially here */
	if (field == FSTART)
		*tree = btree_init (btdata_create (word, FSTART));
	else
		if (*tree == NULL)
			/* If the start file was empty, the binary tree is still null,
			 * so we need to create it, but emphasize that we are now reading
			 * the end file. */
			*tree = btree_init (btdata_create (word, FEND));
		else
			/* A populated tree already exists: attempt inserts instead */
			btree_insert (*tree, word, FEND);

	/* Continue iterating through the file ... */
	while (fgets (buff, BUFFER_SIZE, f) != NULL) {
		size = strlen (buff);
		word = (char *) malloc (sizeof (char) * (size));
		strncpy (word, buff, size);
		word[size-1] = '\0';
		btree_insert (*tree, word, field);
	}

	fclose (f);
	return;
}
